<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <style>
    .router-link-active{
      background:red;
    }
  </style>
</head>
<body>
  <div id="app">
    
    <router-link tag="button" to="/home">到home页</router-link>
    <router-link to="/news">到新闻页</router-link>
    <router-link to="/mine">会员中心</router-link>
    <!-- 出口 -->
    <router-view></router-view>
  </div>
  <script>
    let Home = {
      template:`
        <div>
          <h1>
            我是home页  
          </h1>  
        </div>
      `,
      mounted(){
        
      }
    }
    let Login = {
      template:`
        <div>
          <h1>
            <button @click="login">登录</button>
           
          </h1>  
        </div>
      `,
      methods:{
        login(){
          
          localStorage.setItem('access_token',"dnwie39ud9u39hdf93");
          if(this.$route.params.from){
            this.$router.push(this.$route.params.from);
          }else{
            this.$router.push("/home");
          }
          
        }
      }
    }
    let News = {
      template:`
        <div>
          <h1>
            我是news页  
          </h1>  
        </div>
      `
    }
    let Mine = {
      template:`
        <div>
          <h1>
            会员中心  
          </h1>  
        </div>
      `
    }
    const routes = [
      {
        path:'/',
        redirect:'/home'
      },
      {
        path:"/home",
        component:Home,
        meta:{
          needLogin:false
        }
      },{
        path:"/news",
        component:News,
        meta:{
          needLogin:false
        }
      },{
        path:"/mine",
        component:Mine,
        meta:{
          needLogin:true
        }
      },{
        path:"/login",
        name:"login",
        component:Login,
        meta:{
          
        }
      }
    ];
    // 创建一个路由对象
    const router = new VueRouter({
      routes //定义路由规则
    });
    // 全局前置守卫
    router.beforeEach((to,from,next)=>{
     /* 
     判断是否去 登录 或者 注册
     如果是 直接放行
     2，判断是否登录
      没有登录 重定向到登录
      登录 放行
      */
      console.log(to)
      if( to.fullPath === '/login' ||  to.fullPath === '/register' ){
        next();
      }else{
        // 判断是否登录
        let access_token = localStorage.getItem('access_token');
        if(access_token){
          next();
        }else{
          next({
            name:'login',
            params:{
              from:to.fullPath
            }
          });
        }
      }
    })
    let vm = new Vue({
      el:"#app",
      router
    })
    
  </script>
</body>
</html>